import React, {useEffect, useState, useRef} from 'react';
import {Select, Row, Col, Checkbox, DatePicker, Space} from 'antd';
import LineChartsBookStat from "../../components/HighCharts/LineChartsBookStat";
import {getBookPriceStat} from "@src/services/bookPirceStat";
import styles from './styles.module.less';
import * as PropTypes from "prop-types";

const {Option} = Select;

const { RangePicker } = DatePicker;

RangePicker.propTypes = {
    onChange: PropTypes.func,
    style: PropTypes.shape({width: PropTypes.number})
};
const Leads = () => {
    const [statisticalCenterData, setStatisticalCenterData] = useState([]);
    const [selectedExchange, setSelectedExchange] = useState(null); // 当前选择的交易所
    const [refreshFrequency, setRefreshFrequency] = useState('minute'); // 默认刷新频率为每分钟
    const [refreshSymbol, setRefreshSymbol] = useState('BTC/USDT'); // 默认刷新频率为每分钟
    const intervalRef = useRef(null); // 保存定时器引用
    const [startDate, setStartDate] = useState(null);
    const [endDate, setEndDate] = useState(null);
    const [selectedData, setSelectedData] = useState([
        'avg_price',
        'total_buy_sell_volume',
        'buy_sell_big_volume',
        'buy_sell_near_volume'
    ]);
    useEffect(() => {
        onLoad(); // 初次加载数据

        // 根据刷新频率动态更新数据
        const refreshData = () => {
            console.log(`Refreshing data every ${refreshFrequency}`);
            onLoad(refreshFrequency); // 发送当前频率到后端
        };

        // 清除之前的定时器
        if (intervalRef.current) clearInterval(intervalRef.current);

        // 设置新的定时器
        const intervalTime =
            refreshFrequency === 'minute' ? 60000 :
                refreshFrequency === 'hour' ? 3600000 :
                    86400000; // 每分钟、每小时、每天对应的时间间隔

        intervalRef.current = setInterval(refreshData, intervalTime);

        return () => clearInterval(intervalRef.current); // 清理定时器
    }, [refreshFrequency, refreshSymbol, startDate, endDate]);

    const onLoad = async () => {
        const frequency = refreshFrequency || 'minute'; // 设置默认值
        console.log('当前刷新频率:', frequency);
        const params = {
            frequency,
            symbol : refreshSymbol,
            startDate: startDate ? startDate : "",
            endDate: endDate ? endDate : "",
        };
        const bookPriceStat = await getBookPriceStat(params);
        if (bookPriceStat) {
            setStatisticalCenterData(bookPriceStat);
        }
    };
    const handleExchangeChange = (value) => {
        setSelectedExchange(value); // 更新选中的交易所
    };

    const handleFrequencyChange = (value) => {
        setRefreshFrequency(value); // 更新刷新频率
        // onLoad(value); // 立即请求一次数据
    };

    const handleSymbolChange = (value) => {
        setRefreshSymbol(value); // 更新刷新频率
    };
    const handleDataSelectionChange = (checkedValues) => {
        setSelectedData(checkedValues); // 更新选择的数据项
    };
    const handleDateChange = (dates) => {
        if (dates && dates.length === 2) {
            setStartDate(dates[0]);
            setEndDate(dates[1]);
        } else {
            setStartDate(null);
            setEndDate(null);
        }
    };
    return (
        <div className={styles.home_box}>
            {/* 选择框区域 */}
            <div style={{marginBottom: '16px', display: 'flex', gap: '16px'}}>
                <Select
                    placeholder="Symbol"
                    style={{width: 200}}
                    onChange={handleSymbolChange}
                    defaultValue="symbol"
                >
                    <Option value="BTC/USDT">BTC/USDT</Option>
                    <Option value="DOGE/USDT">DOGE/USDT</Option>
                    <Option value="XRP/USDT">XRP/USDT</Option>
                    <Option value="ETH/USDT">ETH/USDT</Option>
                    <Option value="BNB/USDT">BNB/USDT</Option>
                </Select>
                <Select
                    placeholder="Select Exchange"
                    style={{width: 200}}
                    onChange={handleExchangeChange}
                    allowClear
                >
                    <Option value="All">All</Option>
                    <Option value="binance">Binance</Option>
                    <Option value="okx">OKX</Option>
                    <Option value="cryptocom">Cryptocom</Option>
                </Select>
                <Select
                    placeholder="选择频率"
                    style={{width: 200}}
                    onChange={handleFrequencyChange}
                    defaultValue="minute"
                >
                    <Option value="minute">分钟</Option>
                    <Option value="five_minute">5分钟</Option>
                    <Option value="hour">小时</Option>
                    <Option value="day">每天</Option>
                </Select>
                <Space direction="vertical" style={{ marginBottom: 16 }}>
                    <RangePicker
                        showTime={{ format: 'HH:mm:ss' }}
                        format="YYYY-MM-DD HH:mm:ss"
                        onChange={handleDateChange}
                    />
                </Space>
            </div>
            <div>
                <div style={{marginBottom: '16px'}}>
                    <Checkbox.Group
                        options={[
                            {label: '平均成交价', value: 'avg_price'},
                            {label: '大单挂牌量（买-卖）', value: 'buy_sell_big_volume'},
                            {label: '买单量', value: 'total_buy_volume'},
                            {label: '卖单量', value: 'total_sell_volume'},
                            {label: '挂牌量（买-卖）', value: 'total_buy_sell_volume'},
                            {label: '总的大单买入价值', value: 'total_buy_big_price'},
                            {label: '总的大单卖出价值', value: 'total_sell_big_price'},
                            {label: '大单买卖价值(买-卖)', value: 'total_big_buy_sell_price'},
                            {label: '平均买价', value: 'average_buy_price'},
                            {label: '平均卖价', value: 'average_sell_price'},
                            {label: '中位数卖价', value: 'median_sell_price'},
                            {label: '中位数买价', value: 'median_buy_price'},
                            {label: '中位数买单中每笔数量', value: 'median_sell_volume'},
                            {label: '中位数卖单中每笔数量', value: 'median_buy_volume'},
                            {label: '<100买的数量', value: 'buy_near_volume'},
                            {label: '<100卖单数量', value: 'sell_near_volume'},
                            {label: '<100数量(买-卖)', value: 'buy_sell_near_volume'}
                        ]}
                        value={selectedData}
                        onChange={handleDataSelectionChange}
                    />
                </div>
            </div>

            {/* 图表展示 */}
            {selectedExchange ? (
                // 全屏显示选中的图表
                <div style={{width: '95vw', height: '100vh', background: '#fff'}}>
                    <LineChartsBookStat
                        statisticalCenterData={statisticalCenterData[selectedExchange]}
                        exchange={selectedExchange}
                        frequency={refreshFrequency}
                        selectedData={selectedData}
                    />
                </div>
            ) : (
                // 正常布局显示所有图表
                <>
                    <Row>
                        <Col span={8}>
                            <LineChartsBookStat
                                statisticalCenterData={statisticalCenterData['All']}
                                exchange="All"
                                frequency={refreshFrequency}
                                selectedData={selectedData}
                            />
                        </Col>
                        <Col span={8}>
                            <LineChartsBookStat
                                statisticalCenterData={statisticalCenterData['binance']}
                                exchange="binance"
                                frequency={refreshFrequency}
                                selectedData={selectedData}
                            />
                        </Col>
                        <Col span={8}>
                            <LineChartsBookStat
                                statisticalCenterData={statisticalCenterData['okx']}
                                exchange="okx"
                                frequency={refreshFrequency}
                                selectedData={selectedData}
                            />
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <LineChartsBookStat
                                statisticalCenterData={statisticalCenterData['cryptocom']}
                                exchange="cryptocom"
                                frequency={refreshFrequency}
                                selectedData={selectedData}
                            />
                        </Col>
                    </Row>
                </>
            )}
        </div>
    );
};

export default Leads;
